﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using University.Workshop.Model;
using System.Text.RegularExpressions;
using University.Workshop.DataAccess;
using System.Globalization;

namespace University.Workshop.Business
{
    public static class LogOnManager
    {
        public static User LogOn(string email, string password)
        {
            string emailPattern = @"^(?("")(""[^""]+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
                             @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$";
            try
            {
                if (!Regex.IsMatch(email, emailPattern))
                {
                    throw new BusinessException("Your email or password is incorrect");
                }
                else 
                {
                    if (password != null)
                    {
                        User user = UserDataAccess.UserExists(email, password.GetHashCode().ToString(CultureInfo.InvariantCulture));
                        if (user == null)
                        {
                            throw new BusinessException("Your email or password is incorrect");
                        }
                        else return user;
                    }
                    else return null;
                }
            }
            catch (Exception)
            {
                throw new BusinessException("Your email or password is incorrect");
            }
        }
        public static User GetUser(string email)
        {
            User user = UserDataAccess.GetUserByEmail(email);
            return user;
        }
    }
}
